package a10_动态规划;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * a26_单词拆分复习1
 * </p>
 *
 * @author flyduck
 * @since 2025/2/19
 */
public class a26_单词拆分复习1 {

    public static void main(String[] args) {
        a26_单词拆分复习1 test = new a26_单词拆分复习1();
        System.out.println(test.wordBreak("catsandog", Arrays.asList("cats", "dog", "sand", "and", "cat")));
    }

    //dp[j]：字符串长度为j能不能被字典凑成
    //递推公式：dp[j]
    //从i=1开始遍历到i=j-1
    //dp[j] = dp[i] == true && j - i截取的字符串在wordDict里面
    //初始化：dp[0] = true
    public boolean wordBreak(String s, List<String> wordDict) {
        char[] chars = s.toCharArray();

        boolean[] dp = new boolean[s.length() + 1];
        dp[0] = true;

        for (int j = 1; j <= s.length(); j++) {
            for (int i = 0; i < j; i++) {
                //截取字符串
                //leetcode   i = 2  j = 8
                String splitStr = splitArray(chars, i, j - 1);
                if(wordDict.contains(splitStr) && dp[i] == true){
                    dp[j] = true;
                }
            }
        }
        return dp[s.length()];
    }

    private String splitArray(char[] chars,int leftIdx,int rightIdx){
        char[] result = new char[rightIdx - leftIdx + 1];
        int currentIdx = 0;
        while (leftIdx <= rightIdx){
            result[currentIdx] = chars[leftIdx];
            leftIdx++;
            currentIdx++;
        }
        return new String(result);
    }
}
